<?php

// Ajax request legality check

require_once( 'config.php' );
require_once( 'functions.php' );

// ????????? ?????????? ???? ??????
function db_exception_handler($exception) {
    echo_json_answer( 2, ansi2utf($mxl_error_description[MXL_DATABASE_ERROR]) );
    exit(1);
}

if( !check_ajax_referer() ) {
    header( 'Location: index.php' );
    exit(0);
}

while( true ) {
    if( !isset($_REQUEST['uname']) || ( $uname=trim(strip_tags($_REQUEST['uname'])) ) != $_REQUEST['uname'] || $uname =='' ||
        !isset($_REQUEST['passw']) || ( $passw=trim(strip_tags($_REQUEST['passw'])) ) != $_REQUEST['passw'] || $passw =='' ||
        !isset($_REQUEST['domain'])|| ( $domain=trim(strip_tags($_REQUEST['domain'])) ) != $_REQUEST['domain'] || $domain=='' ||
        !isset($_REQUEST['role']) || ( $role=trim(strip_tags($_REQUEST['role']))) != $_REQUEST['role'] || ( $role !='1' && $role !='2' ))
    {
        $res = array( 'errcode'=>2, 
                      'errmess'=>ansi2utf('??? ???? ??????????? ?????? ???? ??????????? !!!'),
                      'data'=>array('url'=>'') 
                    );
        break;
    }
// ??????????? ? ????? ??
    set_exception_handler('db_exception_handler');

    $db = new PDO("mysql:host=$host_name;dbname=$db_name", $db_user_name, $db_user_pass);
    if( $db->exec('SET CHARACTER SET CP1251') === false ) {
        $res = array( 'errcode'=>2, 
                      'errmess'=>ansi2utf($mxl_error_description[MXL_DATABASE_ERROR]),
                      'data'=>array('url'=>'') 
                    );
        break;
    }

    if( $role == 2 ) {
// ???????? ???????????? domain user
        $res = domain_user_login( $db, $domain, $uname, $passw );
        break;
    }
    
    if( $role == 1 ) {
// ???????? ???????????? domain admin
        if( $uname == $db_user_name && $passw == $db_user_pass )
            $res = main_admin_login( $db, $domain, $uname, $passw );
        else
            $res = domain_admin_login( $db, $domain, $uname, $passw );
     }
    
    break;
}

if( $res['errcode'] != 0 ) sleep( 3 );
    
echo json_encode( $res );
exit(0);

// $res:
// FALSE - database error_
// $res['errcode']:
// 0 - success
// 1 - login fail
// >1 - other fail
//
function main_admin_login( $db, $domain, $uname, $passw ) {
global $db_user_name, $db_user_pass, $mxl_error_description;

    $res = array( 'errcode'=>0, 'errmess'=>'Ok', 'data'=>array('url'=>'') );

    if( $uname != $db_user_name || $passw != $db_user_pass ) {
        $res['errcode'] = 1;
        $res['errmess'] = ansi2utf('??????????????? ?????? ??????? ??????? !!!');
        return $res;
    }
    
	$sqlstr = "SELECT * FROM users WHERE domain=".$db->quote($domain);
    if( ( $recset = $db->query($sqlstr)) === false ) {
        $res['errcode'] = 2;
        $res['errmess'] = ansi2utf($mxl_error_description[MXL_DATABASE_ERROR]);
        return $res;
    }
	
    if( is_bool($row = $recset->fetch(PDO::FETCH_ASSOC)) ) {
        $res['errcode'] = 1;
        $res['errmess'] = ansi2utf('??????????????? ?????? ??????? ??????? !!!');
        return $res;
    }

    session_start();	
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['cat_id']  = $row['cat_id'];
    $_SESSION['amount']  = $row['amount'];
    $_SESSION['uname']   = $row['uname'];
    $_SESSION['domain']  = $row['domain'];

    $res['data']['url'] = 'main.php';
    $recset->closeCursor();

    return $res;
}

function domain_admin_login( $db, $domain, $uname, $passw ) {
global $mxl_error_description;

    $res = array( 'errcode'=>0, 'errmess'=>'Ok', 'data'=>array('url'=>'') );

	$sqlstr = "SELECT * FROM users WHERE domain=".$db->quote($domain).
              " AND uname=".$db->quote($uname)." AND password=".$db->quote(md5($passw));
              
    if( ( $recset = $db->query($sqlstr)) === false ) {
        $res['errcode'] = 2;
        $res['errmess'] = ansi2utf($mxl_error_description[MXL_DATABASE_ERROR]);
        return $res;
    }
	
    if( is_bool($row = $recset->fetch(PDO::FETCH_ASSOC)) ) {
        $res['errcode'] = 1;
        $res['errmess'] = ansi2utf('??????????????? ?????? ??????? ??????? !!!');
        return $res;
    }

    if( $row['status'] == 0 ) {
        $res['errcode'] = 2;
        $res['errmess'] = ansi2utf('???? ? ??????? ??? ??? ???????? ????????.');
        return $res;
    }

    session_start();	
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['cat_id']  = $row['cat_id'];
    $_SESSION['amount']  = $row['amount'];
    $_SESSION['uname']   = $row['uname'];
    $_SESSION['domain']  = $row['domain'];
    
    $res['data']['url'] = 'main.php';
    $recset->closeCursor();

    return $res;
}

function domain_user_login( $db, $domain, $uname, $passw ) {
global $mxl_error_description;

    $res = array( 'errcode'=>0, 'errmess'=>'Ok', 'data'=>array('url'=>'') );

	$sqlstr = "SELECT users.domain as domain, users.user_id as user_id, users.status as `status`,".
              " rcpt_action.rec_id as dom_user_id FROM users LEFT JOIN rcpt_action".
              " ON rcpt_action.user_id = users.user_id AND rcpt_action.name=".$db->quote($uname).
              " AND rcpt_action.password=".$db->quote(md5($passw))." WHERE domain=".$db->quote($domain);
            
    if( ( $recset = $db->query($sqlstr)) === false ) {
        $res['errcode'] = 2;
        $res['errmess'] = ansi2utf($mxl_error_description[MXL_DATABASE_ERROR]);
        return $res;
    }
	
    if( is_bool($row = $recset->fetch(PDO::FETCH_ASSOC)) || !is_numeric($row['dom_user_id'] ) ) {
        $res['errcode'] = 1;
        $res['errmess'] = ansi2utf('??????????????? ?????? ??????? ??????? !!!');
        return $res;
    }

    if( $row['status'] == 0 ) {
        $res['errcode'] = 2;
        $res['errmess'] = ansi2utf('???? ? ??????? ??? ??? ???????? ????????.');
        return $res;
    }

    session_start();	
    $_SESSION['domain']  = strtolower($domain);
    $_SESSION['dom_user'] = strtolower($uname);
    $_SESSION['dom_id']  = $row['user_id'];
    $_SESSION['dom_user_id'] = $row['dom_user_id'];
    
    $res['data']['url'] = 'duser.php';
    $recset->closeCursor();

    return $res;
}
?>